using System;
using System.Collections;
using System.Text;
using UnityEngine;
using UnityEngine.Networking;

namespace MobileMedia
{
    public class UploadImageHandler : MonoBehaviour
    {
        public void UploadImage2Server(string url, Texture2D tex, Action success = null, Action fail = null)
        {
            try
            {
                byte[] bytes = tex.EncodeToPNG();
                Destroy(tex);
                if (bytes != null && bytes.Length > 0)
                {
                    StartCoroutine(Upload(url, bytes, success, fail));
                }
                else
                {
                    fail?.Invoke();
                }
            }
            catch (Exception e)
            {
                fail?.Invoke();
            }
        }

        IEnumerator Upload(string url, byte[] bytes, Action success = null, Action fail = null)
        {
            using (UnityWebRequest www = new UnityWebRequest(url, "POST"))
            {
                www.uploadHandler = new UploadHandlerRaw(bytes);
                www.downloadHandler = new DownloadHandlerBuffer();
                www.SetRequestHeader("Content-Type", "image/png");
                yield return www.SendWebRequest();
                if (IsUploadSucc(www))
                {
                    success?.Invoke();
                }
                else
                {
                    UnityEngine.Debug.LogError("上传头像失败：" + url);
                    fail?.Invoke();
                }
                //(IsUploadSucc(www) ? success : fail)?.Invoke();
            }
        }

        private bool IsUploadSucc(UnityWebRequest www)
        {
            var result = www.downloadHandler?.text;
            if (string.IsNullOrEmpty(result))
                return false;

            var i = result.IndexOf(':');
            if (i == -1 || i == result.Length - 1)
                return false;

            return result[i + 1] == '0';
        }
    }
}